package com.example.demo9.servlet;
import com.example.demo9.mapper.ShoppingMapper;
import com.example.demo9.pojo.Shopping;
import com.example.demo9.utils.MybatisUtils;
import com.google.gson.Gson;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

@WebServlet(name = "ShoppingSerelet",value = "/shopping")
public class ShoppingServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html;charset=UTF-8");
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String method = req.getParameter("method");
        if ("show".equals(method)) {
            // 注意这里调用 showAdv 方法时，也应该正确传递参数
            showShoping(req, resp);
        }else if (method.equals("showDesc")) {
            showDesc(req,resp);

        }

    }

    private void showDesc(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json;charset=UTF-8");
        //根据id号获取广告详情
        String id = req.getParameter("id");
        SqlSession sqlSession = MybatisUtils.getSession();
        ShoppingMapper mapper= sqlSession.getMapper(ShoppingMapper.class);
        Shopping adv = mapper.getAdvById(Integer.parseInt(id));
        HashMap<String,Object> map = new HashMap<>();
        map.put("code",200);
        Object put = map.put("msg", "查询成功");
        map.put("data",adv);
        PrintWriter out = resp.getWriter();
        out.append(new Gson().toJson(map));
    }

    private void showShoping(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//获取SqlSession
    SqlSession sqlSession =MybatisUtils.getSession();
//    获取mapper接口对象
        ShoppingMapper mapper =sqlSession.getMapper(ShoppingMapper.class);
//测试功能

        List<Shopping>   list  = mapper.getShopping();
        HashMap<String,Object> map=new HashMap<>();
        map.put("code",200);
        map.put("total",list.size());
        map.put("rows",list);
        resp.getWriter().append(new Gson().toJson(map));
    }
}
